package com.study.transaction.order.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author: chenhs
 * @date: Created in 10:46 2019/12/17
 **/
@Service
public class OrderService {

    @Autowired
    OrderDatabaseService orderDatabaseService;

    @Autowired
    MQService mqService;


    public void createOrder(JSONObject orderInfo) throws Exception {

        //1、订单信息 - 插入订单系统，订单数据库（事务！）
        // 确保订单有了，才能发送到MQ；所以将事务移至orderDatabaseService中完成。---事务下沉
        orderDatabaseService.saveOrder(orderInfo);

        //todo 此处省略一万行代码
        //2、发送消息到MQ
        mqService.sendMsg(orderInfo);

        //2、通过http接口发送订单信息到 运单系统 （直接调用：不稳定、缺少协调）
        /*String result = callDispatchHttpApi(orderInfo);
        if ("ok".equals(result)) {
            throw new Exception("创建订单失败，原因【运单接口调用失败】！");
        }*/
    }


    /**
     * 通过http接口发送 运单系统，将订单号传过去
     *
     * @param orderInfo
     * @return 接口调用结果
     */
    public String callDispatchHttpApi(JSONObject orderInfo) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //链接超时时间 > 3秒
        requestFactory.setConnectTimeout(3000);
        //处理超时时间 > 2秒
        requestFactory.setReadTimeout(2000);

        //spring提供的一个客户端工具
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String httpUrl = "http://localhost:8080/dispatch-api/dispatch?orderId=" + orderInfo.getString("orderId");
        String result = restTemplate.getForObject(httpUrl, String.class);

        return result;
    }

    public List<JSONObject> listUnDispatch() {
        return orderDatabaseService.listUnDispatch();
    }

}
